import React, { PureComponent } from "react";
import "./index.css";

/**
 * 使用PureComponent解决状态、props或Context未发生变更时的重复diffing问题
 * 注意PureComponent使用的也是浅比较，如果地址不变，就不会重新渲染
 */
export default class Parent extends PureComponent {
    state = { carName: "奔驰C63" };

    changeCar = () => {
        this.setState({ carName: "迈巴赫" });
    };

    // shouldComponentUpdate(nextProps, nextState, nextContext) {
    //     console.log(this.props, this.state, this.context);
    //     console.log(nextProps, nextState, nextContext);
    //     return !this.state.carName === nextState.carName;
    // }

    render() {
        console.log("Parent --- render");

        const { carName } = this.state;

        return (
            <div className="parent">
                <h3>我是Parent组件</h3>
                <span>我的车名字是：{carName}</span>
                <br />
                <button onClick={this.changeCar}>点我换车</button>
                <Child carName="奥拓" />
            </div>
        );
    }
}

class Child extends PureComponent {
    // shouldComponentUpdate(nextProps, nextState, nextContext) {
    //     console.log(this.props, this.state, this.context);
    //     console.log(nextProps, nextState, nextContext);
    //     return !this.props.carName === nextProps.carName;
    // }

    render() {
        console.log("Child --- render");

        return (
            <div className="child">
                <h3>我是Child组件</h3>
                <span>我接到的车是：{this.props.carName}</span>
            </div>
        );
    }
}
